package com.zhu.servlet.user;

import com.zhu.dao.UserDao;
import com.zhu.pojo.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Cookie[] cookies = req.getCookies();
        Object attribute = req.getSession().getAttribute("loginUser");
        if(attribute==null){
            req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req,resp);
            return;
        }

        for (Cookie cookie : cookies) {
            if ("autoLogin".equals(cookie.getName())) {
                resp.sendRedirect("index.do");
                return;
            }
        }
        req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        User user = null;
        try {
            user = new UserDao().getUser(new User(username,password));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        if (user==null){
            req.setAttribute("msg","账号或密码错误");
            req.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(req,resp);
        }else {
            String rememberMe = req.getParameter("autoLogin");
            if (rememberMe!=null){
                Cookie cookie = new Cookie("autoLogin", "c6e50db6-656e-40fd-b559-e4fa1cfcc4f3");
                resp.addCookie(cookie);
            }
            req.getSession().setAttribute("loginUser",user);
            resp.sendRedirect("index.do");
        }
    }
}
